<template>
	<coreshop-page :title="state.formInfo?.name || '表单详情'" mode="left" showLoginModalDom>
		<view class="layout-form-box">
			<view class="form-head">
				<view class="swiper"
					v-if="(state.formInfo?.headType == FormHeadEnum.picture || state.formInfo?.headType == FormHeadEnum.swiper) && state.swiperList.length > 0">
					<uv-swiper :list="state.swiperList" height="400rpx" indicatorActiveColor="#D33123"
						:indicator="state.swiperList.length > 0"></uv-swiper>
				</view>
				<view v-if="state.formInfo?.headType == FormHeadEnum.video">
					<video class="video" :src='state.formInfo?.headTypeVideo'
						:poster="state.formInfo?.headTypeValue"></video>
				</view>
			</view>
			<view class="title-box" v-if="state.formInfo?.description">
				<view calss="title">{{ state.formInfo?.description }}</view>
			</view>
			<!-- 表单主体内容 -->
			<view class="form-content">
				<view class="item-box" v-for="item, index in state.formInfo?.items" :key="item.id">
					<view class="tit-box">
						<view class="tit">{{ item.name }}</view>
						<view class="desc" v-if="item.required">必填</view>
					</view>
					<view class="content-box">
						<!-- 单选 -->
						<template v-if="item.type === FormTypeEnum.radio">
							<uv-radio-group v-model="item.defaultValue">
								<uv-radio v-for="cell, cellIndex in item.radioValue" :key="cellIndex"
									:customStyle="{ 'margin-right': '40rpx','margin-bottom': '20rpx' }" activeColor="#D33123" :name="cell"
									:label="cell"></uv-radio>
							</uv-radio-group>
						</template>
						<!-- 多选 -->
						<template v-if="item.type === FormTypeEnum.checbox">
							<uv-checkbox-group @change="handleChangeChecbox($event, index)">
								<uv-checkbox v-for="cell, cellIndex in item.checkboxValue" :key="cellIndex"
									:checked="cell.checked" :customStyle="{ 'margin-right': '40rpx' ,'margin-bottom': '20rpx' }"
									activeColor="#D33123" :name="cell.value" :label="cell.value"></uv-checkbox>
							</uv-checkbox-group>
						</template>
						<!-- 文本框 -->
						<template v-if="item.type === FormTypeEnum.text">
							<uv-input :placeholder="`请输入${item.name}`" border="surround"
								v-model="item.defaultValue"></uv-input>
						</template>
						<!-- 文本域 -->
						<template v-if="item.type === FormTypeEnum.textarea">
							<uv-textarea v-model="item.defaultValue" :placeholder="`请输入${item.name}`"></uv-textarea>
						</template>
						<!-- 日期 -->
						<template v-if="item.type === FormTypeEnum.date">
							<view class="date" @click="handleOpenDate">{{ item.defaultValue || '请选择日期' }}</view>
							<uv-datetime-picker ref="datePicker" mode="date"
								@confirm="handleDateConfirm($event, index)"> </uv-datetime-picker>
						</template>
						<!-- 时间 -->
						<template v-if="item.type === FormTypeEnum.time">
							<view class="time" @click="handleOpenTime">{{ item.defaultValue || '请选择时间' }}</view>
							<uv-datetime-picker ref="timePicker" mode="time"
								@confirm="handleTimeConfirm($event, index)">
							</uv-datetime-picker>
						</template>
						<!-- 金额 -->
						<template v-if="item.type === FormTypeEnum.money">
							<uv-input :placeholder="`请输入${item.name}`" border="surround"
								v-model="item.defaultValue"></uv-input>
						</template>
						<!-- 密码 -->
						<template v-if="item.type === FormTypeEnum.password">
							<uv-input type="password" :placeholder="`请输入${item.name}`" border="surround"
								v-model="item.defaultValue"></uv-input>
						</template>
						<!-- 省市区 -->
						<template v-if="item.type === FormTypeEnum.area">
							<view class="city" @click="handleOpenSelectCity">{{ item.defaultValue || '请选择省市区' }}</view>
							<coreshop-select-city :show="state.showSelectCity" :cityList="state.cityList"
								@handleClosePicker="handleClosePicker"
								@handleConfirmPicker="handleConfirmPicker($event, index)"></coreshop-select-city>
						</template>
						<!-- 上传 -->
						<template v-if="item.type === FormTypeEnum.image">
							<view class="upload-box">
								<view class="img-box" v-for="cell, cellIndex in item.defaultValue" :key="cell">
									<image class="img" :src="cell"></image>
									<view class="close" @click="handleDelateImg(index, cellIndex)"><uv-icon name="close"
											color="#fff" size="15"></uv-icon></view>
								</view>
								<image class="img" @click="handleUploadAvatar(index)"
									:src="handleStaticResources('/static/images/member/upload.png')"></image>
							</view>
						</template>
						<!-- 坐标 -->
						<template v-if="item.type === FormTypeEnum.coordinate">
							<view class="coordinate-box" @click="handleChooseLocation($event, index)">
								<uv-icon name="empty-address" color="#000" size="20"></uv-icon>
								<view class="m-l-15">{{ item.defaultValue || '点击获取坐标' }}</view>
							</view>
						</template>
						<!-- 商品 -->
						<template v-if="item.type === FormTypeEnum.goods">
							<coreshop-goods-card type="horizontal" imgHeight="140rpx" imgWidth="140rpx"
								:goodsData="hanldeCombinationGoodsData(item.good)">
								<template #goodPrice>
									<view class="price-box">
										<view class="price">￥{{ item.good.price }}</view>
										<view class="spec" @click="handleShowSku(item.good)">
											<view class="tit">选规格</view>
											<view class="num" v-if="item.defaultValue[0]?.nums">
												{{ item.defaultValue[0]?.nums}}
											</view>
										</view>
									</view>
								</template>
							</coreshop-goods-card>

							<!-- 商品sku弹框 -->
							<GoodsDetailSkuPopup :showSku="state.showSku" :goodsDetailData="state.goodsDetailData"
								@handleChangePopup="handleChangePopup" :isShowAddCartBtn="false" btnBuyTitlt="确定"
								@handleBuyNow="handleBuyNow($event, item, index)">
							</GoodsDetailSkuPopup>
						</template>
					</view>
				</view>
			</view>

			<!-- 底部按钮 -->
			<view class="btn-box" @click="handleSubmit">
				<view class="p-20">
					<view class="btn" :style="{ 'background-color': state.formInfo?.buttonColor }">
						{{ state.formInfo?.buttonName }}
					</view>
				</view>
			</view>
		</view>
	</coreshop-page>
</template>
<script setup lang="ts">
	import { reactive, ref } from 'vue';
	import { onLoad, onShareAppMessage, onShareTimeline } from '@dcloudio/uni-app';
	import { queryFormDetial, queryUploadImages, queryAddSubmit } from '@/core/api';
	import type { Response, CityAddressType } from '@/core/models';
	import { handleShowToast, handleStaticResources, handleRouteRedirectTo, handleRouteSwitchTab, chooseImage, getSetting, getShareUrl } from '@/core/utils';
	import { queryAreas } from '@/core/api';
	import { useLoginStore } from '@/core/store';
	import { UserToken, shareUrl } from '@/core/consts';
	import { FormHeadEnum, ShareClientEnum, ShareEnum, ShareModelEnum, FormTypeEnum, PaymentTypeEnum } from '@/core/enum';
	import { timeFormat } from '@/uni_modules/uv-ui-tools/libs/function/index.js';
	import GoodsDetailSkuPopup from '@/pages/components/goods-detail/components/goods-detail-sku/goods-detail-sku.vue';

	interface QueryParams {
		id : number;
	}

	/** 登录store */
	const _useLoginStore = useLoginStore();

	const datePicker = ref();
	const timePicker = ref();

	const state = reactive<{
		formInfo : any;
		id : number;
		swiperList : Array<string>;
		showSelectCity : boolean;
		cityList : Array<any>;
		showSku : boolean;
		goodsDetailData : any;
		paymentType : number,
		shareUrl : string;
	}>({
		formInfo: {},
		id: 0,
		swiperList: [],
		showSelectCity: false,
		cityList: [],
		showSku: false,
		goodsDetailData: {},
		paymentType: 0,
		shareUrl: "",
	})

	onLoad((query : QueryParams) => {
		state.id = Number(query.id);
		/** 获取文章详情 */
		getFormDetial();
		/** 获取城市列表 */
		getAreas();

	})

	/** 获取城市列表 */
	const getAreas = async () => {
		const address : Response<Array<CityAddressType>> = await queryAreas();
		state.cityList = address?.data;
	}

	const getFormDetial = async () => {
		uni.showLoading({
			title: "加载中..."
		})
		const formInfo : Response<any> = await queryFormDetial({
			id: state.id,
			token: uni.getStorageSync(UserToken)
		});
		uni.hideLoading();
		if (formInfo.status) {
			state.formInfo = formInfo.data;

			/** 订单 */
			if (formInfo.data.type == 1) {
				state.paymentType = PaymentTypeEnum.formOrder;
			}
			/** 付款码 */
			if (formInfo.data.type == 2) {
				state.paymentType = PaymentTypeEnum.formPay;
			}

			/** 图片的类型值变为数组 */
			let images = state.formInfo.items.filter((item : any) => item.type === FormTypeEnum.image);
			if (images.length > 0) {
				images.forEach((item : any) => item.defaultValue = []);
			}
			/** 省市区的类型值变为空字符 */
			let citys = state.formInfo.items.filter((item : any) => item.type === FormTypeEnum.area);
			if (citys.length > 0) {
				citys.forEach((item : any) => item.defaultValue = '');
			}
			/** 日期的类型值变为空字符 */
			let dates = state.formInfo.items.filter((item : any) => item.type === FormTypeEnum.date);
			if (dates.length > 0) {
				dates.forEach((item : any) => item.defaultValue = '');
			}
			/** 省市区的类型值变为空字符 */
			let times = state.formInfo.items.filter((item : any) => item.type === FormTypeEnum.time);
			if (times.length > 0) {
				times.forEach((item : any) => item.defaultValue = '');
			}
			/** 商品的类型值变为空数组 */
			let goods = state.formInfo.items.filter((item : any) => item.type === FormTypeEnum.goods);
			if (goods.length > 0) {
				goods.forEach((item : any) => item.defaultValue = []);
			}
			state.swiperList = formInfo.data?.images ? formInfo.data?.images?.split(',') : [];

			/** 获取分享url */
			state.shareUrl = await getShareUrl({
				client: ShareClientEnum.wxMiNiProgram,
				url: shareUrl,
				type: ShareModelEnum.url,
				page: ShareEnum.form,
				params: {
					id: state.id
				}
			})
		} else {
			handleShowToast(formInfo.msg)
		}
	}

	/** 组合商品数据传入组件 */
	const hanldeCombinationGoodsData = (item : any) => {
		return {
			id: item.id,
			image: item.image,
			name: item.name,
			brief: item.brief,
		}
	}

	/** 商品显示sku  */
	const handleShowSku = (data : any) => {
		state.goodsDetailData = data;
		state.showSku = true;
	}

	/** sku弹框显示隐藏 */
	const handleChangePopup = (show : boolean) => {
		state.showSku = show;
	}

	/** sku确定 */
	const handleBuyNow = async ({ productId, nums } : any, item : any, index : number) => {
		state.formInfo.items[index].defaultValue = [{
			key: item.id,
			productId: productId,
			goodsId: item.good.id,
			nums: nums,
			price: item.good.price
		}]
		handleChangePopup(false);
	}

	/** 上传 */
	const handleUploadAvatar = async (index : number) => {
		const imgArr : any = await chooseImage({ count: 3 });
		if (imgArr.tempFilePaths.length > 0) {
			imgArr.tempFilePaths.forEach(async (url : string) => {
				const img : Response<any> = await queryUploadImages(url);
				if (img.status) {
					state.formInfo.items[index].defaultValue.push(img?.data?.src);
				} else {
					handleShowToast('上传失败了');
				}
			})
		}
	}

	/** 删除图片 */
	const handleDelateImg = (index : number, cellIndex : number) => {
		state.formInfo.items[index].defaultValue.splice(cellIndex, 1);
	}

	/** 定位 */
	const handleChooseLocation = (event : any, index : number) => {
		uni.chooseLocation({
			success(e : any) {
				state.formInfo.items[index].defaultValue = e.latitude + ',' + e.longitude;
			},
			async fail() {
				const res : any = await getSetting();
				if (!res.authSetting['scope.userLocation']) {
					uni.openSetting()
				}
			}
		})
	}

	/** 打开省市区选择弹框 */
	const handleOpenSelectCity = () => {
		state.showSelectCity = true;
	}

	/** 关闭省市区选择弹框 */
	const handleClosePicker = () => {
		state.showSelectCity = false;
	}

	/** 省市区确认选择 */
	const handleConfirmPicker = async (data : any, index : number) => {
		state.formInfo.items[index].defaultValue = `${data[0].label} ${data[1].label} ${data[2].label}`;
	}

	/** 多选 */
	const handleChangeChecbox = (e : any, index : number) => {
		state.formInfo?.items[1]?.checkboxValue.forEach((item : any) => {
			item.checked = e.includes(item.value);
		});
	}

	/** 打开日期选择 */
	const handleOpenDate = () => {
		datePicker.value[0].open();
	}

	/** 确认日期 */
	const handleDateConfirm = (e : any, index : number) => {
		state.formInfo.items[index].defaultValue = timeFormat(e.value, 'yyyy-mm-dd');
	}

	/** 打开时间选择 */
	const handleOpenTime = () => {
		timePicker.value[0].open();
	}

	/** 确认时间 */
	const handleTimeConfirm = (e : any, index : number) => {
		state.formInfo.items[index].defaultValue = e.value;
	}

	/** 按钮提交 */
	const handleSubmit = () => {
		_useLoginStore.checkLogin(async () => {

			let data = state.formInfo.items.find((item : any) => item.required && !item.defaultValue);
			if (data) {
				handleShowToast(`${data.name}不能为空`); return;
			}

			/** 判断图片的 */
			let images = state.formInfo.items.find((item : any) => item.type === FormTypeEnum.image && item.required && item.defaultValue.length == 0);
			if (images) {
				handleShowToast(`${images.name}不能为空`); return;
			}

			/** 判断商品的 */
			let goods = state.formInfo.items.find((item : any) => item.type === FormTypeEnum.goods && item.required && item.defaultValue.length == 0);
			if (goods) {
				handleShowToast(`${goods.name}不能为空`); return;
			}

			let submitData = state.formInfo.items.map((item : any) => {
				if (item.type === FormTypeEnum.image) {
					return {
						key: item.id,
						value: item.defaultValue.join(',')
					}
				} else {
					return {
						key: item.id,
						value: item.defaultValue
					}
				}
			});
			const form : Response<any> = await queryAddSubmit({
				data: submitData,
				id: state.id,
				token: uni.getStorageSync(UserToken)
			});
			if (form.status) {
				handleShowToast(form.msg, 'success', () => {
					setTimeout(() => {
						if (state.formInfo.type == 1 || state.formInfo.type == 2) {
							handleRouteRedirectTo(`/pages/order/pay/pay?formId=${form.data.formSubmitId}&orderType=${state.paymentType}&recharge=${form.data.money}`);
						} else {
							handleRouteSwitchTab();
						}
					}, 1000)
				})
			} else {
				handleShowToast(form.msg)
			}
		})
	}

	/** 分享 */
	onShareAppMessage(() => {
		return {
			title: state.formInfo.name,
			path: state.shareUrl
		}
	});
	onShareTimeline(() => {
		return {
			title: state.formInfo.name,
			path: state.shareUrl
		}
	});
</script>
<style lang="scss" scoped>
	@import './detail.scss';
</style>